package com.woan.api.servlet;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.ResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import net.sf.json.JSONObject;

import com.oreilly.servlet.MultipartRequest;
import com.woan.api.idao.SysAdmininfoIDAO;
import com.woan.api.idao.ZbControlIDAO;
import com.woan.api.idao.dao.SysAdmininfoMobileDAO;
import com.woan.api.model.SysAdmininfo;
import com.woan.api.model.SysAdmininfoMobile;
import com.woan.api.model.SysMessage;
import com.woan.api.model.ZbControl;
import com.woan.api.services.MessageServerServices;
import com.woan.api.services.UserServerServices;
import com.woan.api.services.ZbcontrolServerServices;
import com.woan.api.util.CommonUtil;
import com.woan.api.util.CopyFile;
import com.woan.api.util.FuncDate;
import com.woan.api.util.HttpTool;

import com.woan.api.util.Randoms;


//
public class Addtalk extends HttpServlet {
	HttpTool ht = new HttpTool();
	/**
	 * Constructor of the object.
	 */
	public Addtalk() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		long startTime=System.currentTimeMillis();   //获取开始时间
		String oldPath =request.getServletContext().getRealPath("recorder_file_post");
		MultipartRequest multi = null;
		int maxPostSize = 5000 * 1024 * 1024;
		multi = new MultipartRequest(request, oldPath, maxPostSize,"UTF-8");
		Enumeration filesname = multi.getFileNames();//文件
		ResourceBundle rb_config = ResourceBundle.getBundle("config");
		String speaker_audio=rb_config.getString("speaker_audio");
		String speaker_text=rb_config.getString("speaker_text");
		String random_seed=rb_config.getString("random_seed");
		String hash_key=rb_config.getString("hash_key");
		String groupname = multi.getParameter("fristname");
		String username = multi.getParameter("userName");
		String userpwd = multi.getParameter("passwd");
		String devicenum = multi.getParameter("deviceNum");
		String touser = multi.getParameter("touser");
		String vid = multi.getParameter("vid");
		FuncDate fd = new FuncDate();	
		
		ServletContext servletContext = this.getServletContext();     
        WebApplicationContext wac = null;     
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);    
        SysAdmininfoIDAO sysadmininfoiDAO = (SysAdmininfoIDAO) wac.getBean("sysadmininfoiDAO");
        SysAdmininfoMobileDAO sysadmininfomobileiDAO  = (SysAdmininfoMobileDAO) wac.getBean("sysadmininfomobileiDAO");
        ZbControlIDAO zbcontroliDAO  = (ZbControlIDAO) wac.getBean("zbcontroliDAO");
        SysAdmininfo user = null;
		user = sysadmininfoiDAO.FindUserByGroupNameAndUsername(username,touser);
		SysAdmininfoMobile mobile = sysadmininfomobileiDAO.FindAdminMobileByUserid(user.getUid());
		HttpURLConnection connection = null;
		StringBuffer sResult = new StringBuffer();
		try 
		{
			System.out.println("--------------文件上传开始----------------");
			String filename = "";//文件名
			String name1 = (String) filesname.nextElement();
			filename = multi.getFilesystemName(name1);//获取上传文件的名称
			String newFileName = CommonUtil.RandomStrNumDate(4)+filename.substring(filename.lastIndexOf("."));//新的文件名
			System.out.println("newFileName="+newFileName);
			String temp=fd.FindCurSysTime();
			String newPath = oldPath+"/"+temp;//文件保存目录
			File oldFile = new File(oldPath);
			if(!oldFile.exists()){//判断文件夹是否存在，不存在创建
				oldFile.mkdir();
			}
			File newFile = new File(newPath);
			if(!newFile.exists()){//判断文件夹是否存在，不存在创建
				newFile.mkdir();
			}
			File file2 = new File(newPath);
			if(!file2.exists()){//判断文件夹是否存在，不存在创建
				file2.mkdir();
			}
			CopyFile.CopyFile(oldPath+"/"+filename, newPath, newFileName);//复制文件
			CopyFile.doFolder(oldPath+"/"+filename);//删除原来文件
			System.out.println("--------------本地文件生成完成----------------");
			System.out.println("--------------上传给视频服务器开始----------------");
			String to_user_name_really = username+"|"+touser+"|"+mobile.getDeviceNum();
			String fromuser = username;
			String speakurl = speaker_audio+"?dst_username="+to_user_name_really+"&filename="+newFileName+"&hash_key="+hash_key+"&random_seed="+random_seed;
			URL url1 = new URL(speakurl);
			connection=(HttpURLConnection)url1.openConnection();
			//设置请求方式 
			connection.setRequestMethod("POST"); 
			connection.setDoOutput(true);
			byte[] f=new FileUtil().getFileByte(newPath+"/"+newFileName);
			System.out.println("字节数组的大小:"+f.length); 
			// 分隔符 
			String BOUNDARY = "---------------------------7d4a6d158c9"; 
			StringBuffer sb = new StringBuffer(); 
   
			//发送文件: 
			sb = sb.append("--"); 
			sb = sb.append(BOUNDARY); 
			sb = sb.append("\r\n"); 
			sb = sb.append("Content-Disposition: form-data; name=\"s\"; filename=\""+newFileName+"\"\r\n"); 
			sb = sb.append("Content-Type: application/octet-stream\r\n\r\n"); 
			byte[] data = sb.toString().getBytes(); 
			byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 
			//		         设置HTTP头: 
			connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ BOUNDARY); 
			connection.setRequestProperty("Content-Length", String.valueOf(data.length + f.length + end_data.length)); 
			//		         输出: 
			OutputStream outsteam=connection.getOutputStream(); 
			outsteam.write(data); 
			outsteam.write(f); 
			outsteam.write(end_data); 
			outsteam.flush(); 
			//		         读取服务器响应： 
			BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream())); 
			String line=null; 
			while((line=in.readLine())!=null){ 
				if (sResult.length() > 0) {
					sResult.append("\n");
				}
				sResult.append(line);
			} 
			in.close(); 
			outsteam.close(); 
			System.out.println("--------------上传给视频服务器完成----------------");
			ZbControl zbcontrol = new ZbControl();
			String serverinfo=rb_config.getString("serverinfo");
			zbcontrol.setContent(serverinfo+"/recorder_file_post/"+temp+"/"+newFileName);
			//控制类型，1为文字，0为语音
			zbcontrol.setContentType("0");
			zbcontrol.setCreateTime(fd.getSysTime());
			zbcontrol.setVideoId(vid);
			zbcontrol.setFromuser(username);
			zbcontrol.setTouser(touser);
			boolean flag = zbcontroliDAO.SaveMessage(zbcontrol);
			String returnjson = "";
			if(flag)
				returnjson = "{\"results\":0,\"items\":\"\",\"errMsg\":\"成功\"}";
			else
				returnjson = "{\"results\":1,\"items\":\"\",\"errMsg\":\"失败\"}";
			ht.retData(response, returnjson);
				
		} catch (Exception e) {
			System.out.println("e = "+e);
			ht.retData(response, "{\"result\":2}");
		}
		finally
        {
            if (connection != null)
            	connection.disconnect() ;
        }
		long endTime=System.currentTimeMillis(); //获取结束时间
		System.out.println("发送语音消息程序运行时间： "+(endTime-startTime)+"ms");
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	class FileUtil { 

		 public byte[] getFileByte(String fileName) throws FileNotFoundException { 
		  FileInputStream fileInputStream = new FileInputStream(fileName); 
		  return getFileByte(fileInputStream); 
		 }
		 public byte[] getFileByte(URL url) throws IOException { 
			 if (url != null) { 
				 return getFileByte(url.openStream()); 
			 } else { 
				 return null; 
			 } 
		 }
		 public byte[] getFileByte(InputStream in) { 
			  ByteArrayOutputStream out = new ByteArrayOutputStream(4096); 
			  try 
			  { 
				  copy(in, out); 
			  } catch (IOException e) 
			  { 
				  e.printStackTrace(); 
			  } 
			  return out.toByteArray(); 

		 } 
		 private void copy(InputStream in, OutputStream out) throws IOException { 

			 try 
			 { 
				 byte[] buffer = new byte[4096]; 
				 int nrOfBytes = -1; 
				 while ((nrOfBytes = in.read(buffer)) != -1) 
				 { 
					 out.write(buffer, 0, nrOfBytes); 
				 } 
				 out.flush(); 
			 } catch (IOException e) 
			 { 

			 }
			 finally { 
				 try 
				 { 
					 if (in != null) 
					 { 
						 in.close(); 
					 } 
				 } catch (IOException ex) { 
				 } 
				 try { 
					 if (out != null) { 
						 out.close(); 
					 } 
				 } catch (IOException ex) { 
				 } 
			 } 
		 }
	}
}
